/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipUtil {

  /**
   * Unzip the specified file and return extracted dir
   * @param zipPath
   * @return
   */
  public static File unzip(String zipPath) throws FileNotFoundException {
    FileInputStream is = new FileInputStream(zipPath);
    return unzip(is);
  }
  
  public static File unzip(InputStream is) {
    String date = new SimpleDateFormat("yyyyMMdd-HHmmss").format(Calendar.getInstance().getTime());
    File unzipBase = new File(System.getProperty("java.io.tmpdir")+"/oaqa-" + date);
    
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    ZipInputStream in = null;
    try {
      bis = new BufferedInputStream(is);
      in = new ZipInputStream(bis);
      ZipEntry zipEntry = null;
      int data = 0;
      
      while( (zipEntry = in.getNextEntry()) != null ) {
        File targetParent = new File(unzipBase, zipEntry.getName()).getParentFile();
        
        targetParent.mkdirs();
        File targetFile = new File(targetParent, zipEntry.getName());
        bos = new BufferedOutputStream(new FileOutputStream(targetFile));
        
        while( (data = in.read()) != -1 ) {
          bos.write(data);
        }
        
        in.closeEntry();
       
        bos.close();
        bos = null;
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        in.close();
        bis.close();
        bos.close();
      } catch (Exception e2) {}
    }
    
    return unzipBase;
  }
  
}
